import { create } from 'zustand';
import { NavigationItem, NotificationItem, BreadcrumbItem } from '@/types';

// 通知类型
interface ToastNotification {
  id: string;
  type: 'success' | 'error' | 'warning' | 'info';
  title: string;
  message?: string;
  duration?: number;
  action?: {
    label: string;
    onClick: () => void;
  };
}

// 应用状态接口
interface AppState {
  // UI状态
  sidebarOpen: boolean;
  sidebarCollapsed: boolean;
  loading: boolean;
  theme: 'light' | 'dark' | 'auto';
  
  // 导航状态
  navigationItems: NavigationItem[];
  breadcrumbs: BreadcrumbItem[];
  currentPath: string;
  
  // 通知状态
  notifications: NotificationItem[];
  toasts: ToastNotification[];
  unreadNotificationCount: number;
  
  // 搜索状态
  globalSearchOpen: boolean;
  searchQuery: string;
  searchResults: any[];
  searchLoading: boolean;
  
  // 模态框状态
  modals: Record<string, boolean>;
  
  // 动作
  toggleSidebar: () => void;
  setSidebarOpen: (open: boolean) => void;
  toggleSidebarCollapsed: () => void;
  setSidebarCollapsed: (collapsed: boolean) => void;
  setLoading: (loading: boolean) => void;
  setTheme: (theme: 'light' | 'dark' | 'auto') => void;
  
  // 导航动作
  setNavigationItems: (items: NavigationItem[]) => void;
  setBreadcrumbs: (breadcrumbs: BreadcrumbItem[]) => void;
  setCurrentPath: (path: string) => void;
  
  // 通知动作
  addNotification: (notification: Omit<NotificationItem, 'id'>) => void;
  markNotificationAsRead: (id: string) => void;
  markAllNotificationsAsRead: () => void;
  removeNotification: (id: string) => void;
  clearNotifications: () => void;
  
  // Toast动作
  showToast: (toast: Omit<ToastNotification, 'id'>) => void;
  removeToast: (id: string) => void;
  clearToasts: () => void;
  
  // 搜索动作
  setGlobalSearchOpen: (open: boolean) => void;
  setSearchQuery: (query: string) => void;
  setSearchResults: (results: any[]) => void;
  setSearchLoading: (loading: boolean) => void;
  performSearch: (query: string) => Promise<void>;
  
  // 模态框动作
  openModal: (modalId: string) => void;
  closeModal: (modalId: string) => void;
  toggleModal: (modalId: string) => void;
  closeAllModals: () => void;
}

// 生成唯一ID
const generateId = () => `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

// 应用状态存储
export const useAppStore = create<AppState>((set, get) => ({
  // 初始状态
  sidebarOpen: true,
  sidebarCollapsed: false,
  loading: false,
  theme: 'light',
  
  navigationItems: [],
  breadcrumbs: [],
  currentPath: '/',
  
  notifications: [],
  toasts: [],
  unreadNotificationCount: 0,
  
  globalSearchOpen: false,
  searchQuery: '',
  searchResults: [],
  searchLoading: false,
  
  modals: {},
  
  // UI动作
  toggleSidebar: () => {
    set((state) => ({ sidebarOpen: !state.sidebarOpen }));
  },
  
  setSidebarOpen: (open: boolean) => {
    set({ sidebarOpen: open });
  },
  
  toggleSidebarCollapsed: () => {
    set((state) => ({ sidebarCollapsed: !state.sidebarCollapsed }));
  },
  
  setSidebarCollapsed: (collapsed: boolean) => {
    set({ sidebarCollapsed: collapsed });
  },
  
  setLoading: (loading: boolean) => {
    set({ loading });
  },
  
  setTheme: (theme: 'light' | 'dark' | 'auto') => {
    set({ theme });
    // 保存到localStorage
    localStorage.setItem('app-theme', theme);
  },
  
  // 导航动作
  setNavigationItems: (navigationItems: NavigationItem[]) => {
    set({ navigationItems });
  },
  
  setBreadcrumbs: (breadcrumbs: BreadcrumbItem[]) => {
    set({ breadcrumbs });
  },
  
  setCurrentPath: (currentPath: string) => {
    set({ currentPath });
  },
  
  // 通知动作
  addNotification: (notification: Omit<NotificationItem, 'id'>) => {
    const newNotification: NotificationItem = {
      ...notification,
      id: generateId(),
      read: false,
      createdAt: new Date().toISOString(),
    };
    
    set((state) => ({
      notifications: [newNotification, ...state.notifications],
      unreadNotificationCount: state.unreadNotificationCount + 1,
    }));
  },
  
  markNotificationAsRead: (id: string) => {
    set((state) => {
      const notifications = state.notifications.map((notification) =>
        notification.id === id ? { ...notification, read: true } : notification
      );
      
      const unreadCount = notifications.filter((n) => !n.read).length;
      
      return {
        notifications,
        unreadNotificationCount: unreadCount,
      };
    });
  },
  
  markAllNotificationsAsRead: () => {
    set((state) => ({
      notifications: state.notifications.map((notification) => ({
        ...notification,
        read: true,
      })),
      unreadNotificationCount: 0,
    }));
  },
  
  removeNotification: (id: string) => {
    set((state) => {
      const notifications = state.notifications.filter((n) => n.id !== id);
      const unreadCount = notifications.filter((n) => !n.read).length;
      
      return {
        notifications,
        unreadNotificationCount: unreadCount,
      };
    });
  },
  
  clearNotifications: () => {
    set({
      notifications: [],
      unreadNotificationCount: 0,
    });
  },
  
  // Toast动作
  showToast: (toast: Omit<ToastNotification, 'id'>) => {
    const newToast: ToastNotification = {
      ...toast,
      id: generateId(),
      duration: toast.duration || 5000,
    };
    
    set((state) => ({
      toasts: [...state.toasts, newToast],
    }));
    
    // 自动移除Toast
    if (newToast.duration && newToast.duration > 0) {
      setTimeout(() => {
        get().removeToast(newToast.id);
      }, newToast.duration);
    }
  },
  
  removeToast: (id: string) => {
    set((state) => ({
      toasts: state.toasts.filter((toast) => toast.id !== id),
    }));
  },
  
  clearToasts: () => {
    set({ toasts: [] });
  },
  
  // 搜索动作
  setGlobalSearchOpen: (globalSearchOpen: boolean) => {
    set({ globalSearchOpen });
    if (!globalSearchOpen) {
      set({ searchQuery: '', searchResults: [] });
    }
  },
  
  setSearchQuery: (searchQuery: string) => {
    set({ searchQuery });
  },
  
  setSearchResults: (searchResults: any[]) => {
    set({ searchResults });
  },
  
  setSearchLoading: (searchLoading: boolean) => {
    set({ searchLoading });
  },
  
  performSearch: async (query: string) => {
    if (!query.trim()) {
      set({ searchResults: [] });
      return;
    }
    
    set({ searchLoading: true });
    
    try {
      // 这里将调用搜索API
      const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
        },
      });
      
      if (response.ok) {
        const results = await response.json();
        set({ searchResults: results, searchLoading: false });
      } else {
        set({ searchResults: [], searchLoading: false });
      }
    } catch (error) {
      console.error('搜索失败:', error);
      set({ searchResults: [], searchLoading: false });
    }
  },
  
  // 模态框动作
  openModal: (modalId: string) => {
    set((state) => ({
      modals: { ...state.modals, [modalId]: true },
    }));
  },
  
  closeModal: (modalId: string) => {
    set((state) => ({
      modals: { ...state.modals, [modalId]: false },
    }));
  },
  
  toggleModal: (modalId: string) => {
    set((state) => ({
      modals: { ...state.modals, [modalId]: !state.modals[modalId] },
    }));
  },
  
  closeAllModals: () => {
    set({ modals: {} });
  },
}));

// 快捷钩子
export const useAppUI = () => {
  const {
    sidebarOpen,
    sidebarCollapsed,
    loading,
    theme,
    toggleSidebar,
    setSidebarOpen,
    toggleSidebarCollapsed,
    setSidebarCollapsed,
    setLoading,
    setTheme,
  } = useAppStore();
  
  return {
    sidebarOpen,
    sidebarCollapsed,
    loading,
    theme,
    toggleSidebar,
    setSidebarOpen,
    toggleSidebarCollapsed,
    setSidebarCollapsed,
    setLoading,
    setTheme,
  };
};

export const useAppNotifications = () => {
  const {
    notifications,
    toasts,
    unreadNotificationCount,
    addNotification,
    markNotificationAsRead,
    markAllNotificationsAsRead,
    removeNotification,
    clearNotifications,
    showToast,
    removeToast,
    clearToasts,
  } = useAppStore();
  
  return {
    notifications,
    toasts,
    unreadNotificationCount,
    addNotification,
    markNotificationAsRead,
    markAllNotificationsAsRead,
    removeNotification,
    clearNotifications,
    showToast,
    removeToast,
    clearToasts,
  };
};

export const useAppSearch = () => {
  const {
    globalSearchOpen,
    searchQuery,
    searchResults,
    searchLoading,
    setGlobalSearchOpen,
    setSearchQuery,
    setSearchResults,
    setSearchLoading,
    performSearch,
  } = useAppStore();
  
  return {
    globalSearchOpen,
    searchQuery,
    searchResults,
    searchLoading,
    setGlobalSearchOpen,
    setSearchQuery,
    setSearchResults,
    setSearchLoading,
    performSearch,
  };
};

export const useAppModals = () => {
  const {
    modals,
    openModal,
    closeModal,
    toggleModal,
    closeAllModals,
  } = useAppStore();
  
  return {
    modals,
    openModal,
    closeModal,
    toggleModal,
    closeAllModals,
    isModalOpen: (modalId: string) => !!modals[modalId],
  };
};